
import java.io.FileInputStream
import java.util.Properties

import org.apache.hadoop.hive.conf.HiveConf
import org.apache.hadoop.hive.ql.Driver
import org.apache.hadoop.hive.ql.session.SessionState
import org.slf4j.LoggerFactory

import scala.xml._

class HiveAuth{
  private val LOG = LoggerFactory.getLogger(classOf[HiveAuth])

  /**
    * 对外接口 用于验证SQL语法和操作权限
    * @param username 用户名
    * @param cmd SQL语句
    * @return （错误码 正确为0，错误信息 正确为null）
    */

  def query(username: String, cmd: String) = {
    //  读取配置文件
    val properties = new Properties()
    //   配置信息
    val path1:String = Thread.currentThread().getContextClassLoader.getResource("application.properties").getPath
    properties.load(new FileInputStream(path1))
    val hive_sitePath:String = properties.getProperty("hive.site")

    System.setProperty("HADOOP_USER_NAME", username)

    val path = Thread.currentThread().getContextClassLoader.getResource("config/"+hive_sitePath+".xml").getPath

    val xmlFile = XML.loadFile(path)

    // 解析hive-site.xml 设置属性
    val a = xmlFile \ "property"
    a.foreach{node =>
      val n = (node \ "name").head match{
        case <name>{t}</name> => t
        case _ => None
      }
      val v = (node \ "value").head match{
        case <value>{t}</value> => t
        case _ => None
      }

      if(v != None && n != None)
        System.setProperty(n.toString, v.toString)
    }

    val conf = new HiveConf(this.getClass)
    println("this.class:"+this.getClass)
    println("conf:"+conf)
    LOG.info("this.class:"+this.getClass)
    LOG.info("conf:"+conf)
    LOG.info("SessionState.start(conf)")
    SessionState.start(conf)
    SessionState.get().setIsSilent(true)
    LOG.info("driver = new Driver(conf)")
    val driver = new Driver(conf)
    LOG.info("driver.init()")
    driver.init()
    LOG.info("val (errCode, errMsg) = run(cmd, driver)")
    val (errCode, errMsg) = run(cmd, driver)

    driver.destroy()

    (errCode, errMsg)
  }

  def run(q: String, driver: Driver): (Int, String) = {
    try {
      LOG.info("run(cmd, driver)  starting--------")
      val response = driver.compileAndRespond(q)
//      val response = driver.compile(q);
      println(response)
      LOG.info("response"+response)
      (response,null)
      if (response.getResponseCode != 0)
        (response.getResponseCode, response.getErrorMessage)
      else
        (0, null)
    }
    catch{
      case e: Exception =>(-1, e.getMessage)

    }
  }

}

object HiveAuth {

  def main(args: Array[String]): Unit = {

    val (errCode, errMsg) = HiveAuth().query("beta_bdpss", "select * from test limit 10")

    println(s"errCode = $errCode  errMsg=$errMsg")

  }

  def apply(): HiveAuth = new HiveAuth()

}
